﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Cashier_Model;
using Cashier_Service;
using Cashier.utils;
using System.Collections;
using Cashier_Utils;

namespace Cashier.rights
{
    public partial class AdminAddForm : Form
    {
        private RightsForm rightsform;
        private Admin admin;
        private long adminid;
        private MainForm mainform;
        private AdminService adminService;
        private String oldPassword;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="rightsform"></param>
        /// <param name="adminid"></param>
        public AdminAddForm(MainForm mainform, RightsForm rightsform, long adminid)
        {
            InitializeComponent();
            this.rightsform = rightsform;
            this.mainform = mainform;
            this.adminid = adminid;
            this.adminService = new AdminService();

            this.label7.Visible = false;
            this.comboBox_storeInfo.Visible = false;

            if (adminid > 0)
                button_save.Tag = "user_edit";
            else
                button_save.Tag = "user_add";
            Button[] buttons = { button_save };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);
            this.InitialComboBox();
            this.InitialFormData();

            if (adminid > 0)
            {
                Admin queryAdmin = this.adminService.GetAdmin(adminid);
                if (queryAdmin!=null && queryAdmin.Isadmin)
                {
                    comboBox_role.Enabled = false;
                }
                comboBox_role.SelectedValue = queryAdmin.Roleid;
                if (!String.IsNullOrEmpty(queryAdmin.StoreNo))
                {
                    comboBox_storeInfo.SelectedValue = queryAdmin.StoreNo;
                }
            }
        }

        #region 功能方法实现

        /// <summary>
        /// 初始化角色
        /// </summary>
        private void InitialComboBox()
        {
            try
            {
                DataTable dt = new RoleService().GetRoleTable(0, 0);
                comboBox_role.DataSource = dt;
                comboBox_role.DisplayMember = "name";
                comboBox_role.ValueMember = "id";

                StoreInfo storeInfo = new StoreInfo();
                storeInfo.Ascfield = "id";
                storeInfo.Pagesize = 0;
                DataTable storeDt = new StoreInfoService().GetStoreInfoTable(storeInfo);
                comboBox_storeInfo.DataSource = storeDt;
                comboBox_storeInfo.DisplayMember = "name";
                comboBox_storeInfo.ValueMember = "store_no";
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 初始化表单数据
        /// </summary>
        private void InitialFormData()
        {
            try
            {
                if (adminid > 0)
                {
                    this.admin = adminService.GetAdmin(adminid);
                    if (admin != null)
                    {
                        textbox_username.Enabled = false;
                        textbox_password.Isvalidate = false;
                        textbox_repassword.Isvalidate = false;
                        this.oldPassword = admin.Password;
                        FormUtil.InitialFormData(admin, this.groupBox1, 1);
                    }
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 保存管理员
        /// </summary>
        private void SaveAdmin()
        {
            ArrayList list = new ArrayList();
            FormUtil.GetValidateControlsNotPassed(this, list, 1);
            if (list.Count > 0)
                return;

            String repassword = textbox_repassword.Text.Trim();
            if (!String.IsNullOrEmpty(repassword) && !repassword.Equals(textbox_password.Text.Trim()))
            {
                MessageBox.Show("两次输入的密码不匹配！");
                return;
            }

            if (admin == null)
                admin = new Admin();
            FormUtil.GetFormData(admin, this.groupBox1, 1);

            if (adminService.ExistSameUsername(adminid, textbox_username.Text.Trim()))
            {
                MessageBox.Show("登录用户名重复！");
                return;
            }

            bool issuccess = false;
            if (!String.IsNullOrEmpty(admin.Password))
                admin.Password = EncryptionUtil.Md5(admin.Password);
            else
                admin.Password = this.oldPassword;

            admin.EnterpriseNo = mainform.Admin.EnterpriseNo;
            admin.Roleid = Int64.Parse(comboBox_role.SelectedValue.ToString());
            if (comboBox_storeInfo.SelectedValue != null)
            {
                admin.StoreNo = comboBox_storeInfo.SelectedValue.ToString();
            }
            admin.StoreNo = mainform.Admin.StoreNo;
            if (admin.Id > 0)
            {
                int flag = adminService.UpdateAdmin(admin);
                if (flag > 0)
                    issuccess = true;
            }
            else
            {
                admin.Createdby = mainform.Admin.Name;
                admin.Createtime = DateTime.Now;
                long id = adminService.InsertAdmin(admin);
                if (id > 0)
                {
                    admin.Id = id;
                    issuccess = true;
                }
            }

            if (issuccess)
            {
                DialogResult result = MessageBox.Show("保存成功，是否添加新记录！", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    admin = null;
                    FormUtil.ClearFormData(this.groupBox1, 1);
                }
                else
                {
                    rightsform.InitialAdminListBox();
                    this.Close();
                }
            }
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_save_Click(object sender, EventArgs e)
        {
            this.SaveAdmin();
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region 重写方法

        /// <summary>
        /// 重写键盘事件
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool b = base.ProcessCmdKey(ref msg, keyData);
            switch (keyData)
            {
                case Keys.Escape:
                    this.Close();
                    break;
                case Keys.F5:
                    this.SaveAdmin();
                    break;
            }
            return b;
        }

        #endregion

    }
}
